App.define('ui', ['ajax', 'user'], (function () {
	var ui = {};
	try {
		var pages = {}, currentPageId, $pageContainer = $('#page-container'), $overlay = $('#overlay');
		ui.addPage = function (page) {
			pages[page.id] = page;
		};

		App.addPage = ui.addPage;

		App.addNewPage = function (p) {
			ui.addPage(new ui.Page(p));
		};

		ui.setTitle = function (title) {
			App.isUndefined(title) || title === '' || (document.title = title + ' - ' + App.name);
		};

		ui.goTo = function (p) {
			if ('string' == typeof p && ui.getPage(p)) {
				openPage(ui.getPage(p));
			} else {
				App.loadScript(toPageUrl(p), function (success) {
					if (success) {
						openPage(ui.getPage(p));
					}
				});
			}

			function openPage(page) {
				$overlay.show();
				App.ajax({
					url: page.url,
					success: function (response) {
						currentPageId = page.id;
						ui.setTitle(page.title);
						$(document.body).css('overflow', 'hidden');
						$pageContainer.html(response);
						if (!App.isUndefined(page.init)) {
							App.require(page.require, function (success) {
								if (success) {
									page.init();
									$(document.body).css('overflow', 'auto');
									$overlay.hide();
								}
							});
						}
					}
				});
			}
		};
		App.goToPage = ui.goTo;

		function toPageUrl(page) {
			return App.config.baseUrl
				+ 'pages/{page}.page{.min}.js'
				.replace('{page}', page)
				.replace('{.min}', App.config.debug ? '' : '.min');
		}

		ui.getCurrentPage = function () {
			return ui.getPage(currentPageId);
		};

		ui.getPage = function (id) {
			return pages[id];
		};

		ui.Page = function (p) {
			var self = this;
			p = p || {};
			self.id = p.id || 'index';
			self.url = p.url || 'index.html';
			self.title = p.title || '';
			self.init = p.init;
			self.require = p.require;
			self.show = function () {
				App.ui.goTo(self);
			};
			return self;
		};

		App.Page = ui.Page;

	} catch (e) {
		console.error('ui.module.js', e);
	}

	ui.complited = function() {
		if (!App.isUndefined(App.config.homePage)) {
			ui.goTo(App.config.homePage);
		}
	};

	return ui;
})());